package com.example.singleton;

import lombok.extern.slf4j.Slf4j;

/**
 * 单例模式，全程只有一个实例
 */
@Slf4j
public class Singleton {
    //使用volatile，开启多线程下的可见性
    private static volatile Singleton instance;

    public Singleton() {
    }

    //懒汉式，使用的时候才开始创建
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                    log.info("Singleton initialized");
                }
            }
        }

        return instance;
    }

    public static void main(String[] args) {
        new Thread(() -> Singleton.getInstance(), "t1").start();
        new Thread(() -> Singleton.getInstance(), "t2").start();
    }
}
